<?php
class Tele extends Controller {

    private $aPost;

    function Tele() {

        parent::Controller();
        $this->load->model('model_tele');
        $this->load->model('model_telesched');
        $this->load->model('model_mailer');

        //verificare sesiune
        if (!$this->usersession->userLoggedIn()) {
            $aResponse = array("error" => true, "description" => "Sesiunea a expirat", "type" => "nosession");
            die(json_encode($aResponse));
        }
        copyPost($this->aPost);
        $this->aUser = $this->usersession->currentUser();
    }

    /**
     * Functie care aduce datele in grid
     */
    function getContact() {
        echo json_encode($this->model_tele->getContact($this->aPost));
    }

    /**
     * Functie care aduce datele unui contact de telemarketing
     */
    function getTeleContact() {
        $aResponse = array();
        $aResponse["tele_contact"] = $this->model_tele->getTeleContact($this->aPost);
        $aResponse["tele_answerfree"] = $this->model_tele->getClientAnswerFree($this->aPost);
        $aResponse["tele_sched"] = $this->model_telesched->getData($this->aPost);
        $aResponse["tele_answer"] = $this->model_tele->getClientAnswer($this->aPost);
        $aResponse["tele_custom"] = $this->model_tele->getCustomAnswers($this->aPost);


        echo json_encode($aResponse);
    }

    /**
     * Salvare contact telemarketing
     * @return void
     */
    function saveTeleContact() {
        if ($this->aPost["client_persons_id"] == "") {
            $aResponse = array("error" => true, "description" => "Nu aveti voie sa salvati", "type" => "Validare");
            echo  json_encode($aResponse);
            return;
        }
        $this->model_tele->saveTeleContact($this->aPost);
        $aResponse = array("error" => false, "success" => true, "description" => "Datele au fost salvate");
        echo  json_encode($aResponse);
    }

    /**
     * Transfer contacte la un user
     * @return void
     */
    function transferContact() {
        $bResult = $this->model_tele->transferContact($this->aPost);
        if ($bResult === TRUE) {
            $aResponse = array("error" => false, "success" => true, "description" => "Contactele au fost salvate");
        }
        else {
            $aResponse = array("error" => true, "description" => $bResult);
        }
        echo json_encode($aResponse);
    }


    /**
     * Returnare raspunsuri contact telemarketing
     * @return void
     */
    function getClientAnswer() {
        if (isset($this->aPost["xaction"]) && ($this->aPost["xaction"] == "update") && (isset($this->aPost["client_persons_id"])) && ($this->aPost["client_persons_id"] > 0)) {
            $this->saveAnswer();
            return;
        }

        echo json_encode($this->model_tele->getClientAnswer($this->aPost));
    }

    /**
     * Functie de modificare raspuns
     * @return string json
     */
    function saveAnswer() {
        $bResponse = $this->model_tele->saveAnswer($this->aPost);

        if ($bResponse === TRUE) {
            $aResponse = array("error" => false, "success" => true, "description" => "Datele au fost salvate");
        }
        else {
            $aResponse = array("error" => false, "success" => true, "description" => $bResponse, "type" => "Validare");
        }
        echo  json_encode($aResponse);
    }

    /**
     * Returnare raspunsuri contact telemarketing
     * @return void
     */
    function getClientAnswerFree() {
        if (isset($this->aPost["xaction"]) && ($this->aPost["xaction"] == "update") && (isset($this->aPost["client_persons_id"])) && ($this->aPost["client_persons_id"] > 0)) {
            $this->saveAnswerFree();
            return;
        }
        echo json_encode($this->model_tele->getClientAnswerFree($this->aPost));
    }

    /**
     * Functie de modificare raspuns
     * @return string json
     */
    function saveAnswerFree() {
        $bResponse = $this->model_tele->saveAnswerFree($this->aPost);

        if ($bResponse === TRUE) {
            $aResponse = array("error" => false, "success" => true, "description" => "Datele au fost salvate");
        }
        else {
            $aResponse = array("error" => false, "success" => true, "description" => $bResponse, "type" => "Validare");
        }
        echo  json_encode($aResponse);
    }


    /**
     * Returnare campuri custom contact telemarketing
     * @return void
     */
    function getCustomAnswers() {
        if (isset($this->aPost["xaction"]) && ($this->aPost["xaction"] == "update") && (isset($this->aPost["client_persons_id"])) && ($this->aPost["client_persons_id"] > 0)) {
            $this->saveCustomAnswer();
            return;
        }

        echo json_encode($this->model_tele->getCustomAnswers($this->aPost));
    }

    /**
     * Functie de modificare raspuns custom
     * @return string json
     */
    function saveCustomAnswer() {
        $bResponse = $this->model_tele->saveCustomAnswer($this->aPost);

        if ($bResponse === TRUE) {
            $aResponse = array("error" => false, "success" => true, "description" => "Datele au fost salvate");
        }
        else {
            $aResponse = array("error" => false, "success" => true, "description" => $bResponse, "type" => "Validare");
        }
        echo  json_encode($aResponse);
    }


    /**
     * Returnare log contact telemarketing
     * @return void
     */
    function getLog() {
        echo json_encode($this->model_tele->getLog($this->aPost));
    }

    /**
     * Returnare log contact telemarketing
     * @return void
     */
    function getLogGeneral() {
        echo json_encode($this->model_tele->getLogGeneral($this->aPost));
    }

    /**
     * Trimitere email
     * @return int
     */
    function sendMail() {
        $aResponse = array("error" => false, "description" => "Emailul s-a trimis !");
        $aContact = $this->model_tele->getTeleContact($this->aPost);		
        $aContact = arrayToObject($aContact);

        $iContact = $this->input->post("client_persons_id");
        $aEmployees = $this->config->item("employeeContact");
        $path_full = $this->config->item('upload_path_full');
        $email = $this->input->post("email");
        $mailer_id = $this->input->post("mailer_id");


        $this->load->model("model_mailer");
        $this->load->plugin('phpmailer');
        $mail = new phpmailer(true);

        $aResult = $this->db->get_where("mailer", array("mailer_id" => $mailer_id));
        if ($aResult->num_rows() != 1) {
            $aResponse = array("error" => false, "success" => true, "description" => "Mailerul nu mai exista !");
            echo json_encode($aResponse);
            return;
        }
        $aTask = $aResult->row();
		
		
		if ($aContact->unsubscribed == 1) {
			 $aResponse = array("error" => false, "success" => true, "description" => "Contactul a fost dezabonat");
            echo json_encode($aResponse);
            return;
		}
		


        /// LOGO + SEMNATURA
        $this->db->where("user_id", $this->aUser["user_id"]);
        $aUser = $this->db->get("user")->row_array();

        $this->db->where("code", "logo");
        $sLogo = $this->db->get("settings")->row()->value;

        $filename = "././resources/logo/" . $sLogo;
        $bodySign = $aUser["sign"];

        if (file_exists($filename)) {

            $pattern = '/_LOGO/';
            preg_match_all($pattern, $bodySign, $matches);

            if (count($matches[0]) > 0) {
                //scot calea relativa
                $bodySign = str_replace($path_full, "", $bodySign);
                //$sReplace="cid:".$attach["name"];
                $aReplace = explode(".", $sLogo);
                array_pop($aReplace);
                $base = implode(".", $aReplace);
                $sReplace2 = "cid:" . $base;

                $bodySign = str_replace("_LOGO", "<img src='$sReplace2'  />", $bodySign);
				$bodySign .= "<br>";
                $mail->AddEmbeddedImage($filename, $base, $sLogo);
            }
        }


        $mail->IsHTML(true);
        $mail->CharSet = "utf-8";
        $mail->IsSMTP();
        $mail->SMTPAuth = true;
		
		$mail->Host = "mail.morethanpub.ro";
			$mail->Password = "officeoffice";
			$mail->Username = "office@morethanpub.ro";
		
        /*$mail->Host = "comunicatedirectmarketing.ro";
		$mail->Password = "marketing2006";
			$mail->Username = "office@comunicatedirectmarketing.ro";*/
			
			/*$mail->Password = "bookbook2013";
			$mail->Username = "bookland@comunicatedirectmarketing.ro";*/
        $mail->Port = 26;
        

        $body = $aTask->body;
		
		//se preia id-ul de mailer
	    $this->load->model("model_mailer");
        $resultLink = $this->model_mailer->bringLink("mailer_link", $aTask->mailer_id, 0, 1000, "link_nume", "ASC");
        $resultLink = $resultLink["DS_LINK"];
        $satelit = $this->config->item("mtp_satelit");
	    $satelitDezabonare = $this->config->item("mtp_satelit_dezabonare");

        foreach ($resultLink as $key => $aLink) {
        	$aLinkEncoded = base64_encode($aLink["link_nume"] . "-**-" . $aContact->client_persons_id . "-**-" . $aLink["link_id"] . "-**-" . md5($aLink["link_id"] + ($aContact->client_persons_id * 22)));
			$aLinkEncoded = str_replace("/", "_", $aLinkEncoded);
	        $body = str_replace($aLink["link_cod"], $satelit . $aLinkEncoded, $body);
        }
		
		//creare link dezabonare
		$aLinkDezabonare= base64_encode($aContact->client_persons_id . "-**-" . md5($aContact->client_persons_id * 22));
		$aLinkDezabonare = str_replace("/", "_", $aLinkDezabonare);
		$aLinkDezabonare = $satelitDezabonare . $aLinkDezabonare;		
		
        $name = $aContact->fname . " " . $aContact->lname;

        if ($aContact->sex == "2") {
            $header_lower = strtolower($aTask->header_m) . " " . $name;
            $header_title = ucfirst($aTask->header_m) . " " . $name;
            $header_ = $aTask->header_m . " " . $name;
        }
        elseif ($aContact->sex == "1") {
            $header_lower = strtolower($aTask->header_f) . " " . $name;
            $header_title = ucfirst($aTask->header_f) . " " . $name;
            $header_ = $aTask->header_f . " " . $name;
        }
        else {
            $header_lower = strtolower($aTask->header_n) . " " . $name;
            $header_title = ucfirst($aTask->header_n) . " " . $name;
            $header_ = $aTask->header_n . " " . $name;
        }


        //replacing customizari nume
        $strReplace1 = array(
            "LOWER_HEADER", "TITLE_HEADER", "NAME", "_HEADER", "_DISCLAIMER", "_COMPANY", "_ADDRESS", "_PHONE",
            "_MOBIL", "_WEB", "_CUI", "_DOMAIN", "_SUBDOMAIN", "_EMAIL1", "_EMAIL2", "_POSITION", "_SUBPOSITION",
            "_EMPLOYEE", "_COUNTY", "_CITY" ,"PRENUME", "NUME","_DEZABONAT");
        $strReplace2 = array(
            $header_lower, $header_title, $name, $header_, $bodySign . $aTask->disclaimer, $aContact->company,
            $aContact->address, $aContact->phone, $aContact->mobil, $aContact->web, $aContact->cui,
            $aContact->domain_name, $aContact->domain_sub_name, $aContact->email, $aContact->email2,
            $aContact->position_name, $aContact->position_sub_name, $aEmployees[$aContact->employees],
            $aContact->county_name, $aContact->city_name,  $aContact->fname,  $aContact->lname, $aLinkDezabonare);

        $body = str_replace($strReplace1, $strReplace2, $body);
		$mail->Subject = str_replace($strReplace1, $strReplace2, $aTask->subject);
		 
        $aAttachment = $this->model_mailer->bringAttach("mailer_attach", $aTask->mailer_id, "attach", 0, 1000, "name", "asc");
        foreach ($aAttachment["DS_ATTACH"] as $attach) {

            if ($attach["name"] != '') {
                $filename = "././resources/uploads/attach/" . $attach["name"];
                if (file_exists($filename)) {
                    $mail->AddAttachment($filename);
                }
                else {
                    $aResponse = array("error" => true, "description" => "Un atasament nu exista", "error_no" => "2");
                }
            }
        }


        //imagini embedded
        $aAttachment = $this->model_mailer->bringAttach("mailer_attach", $aTask->mailer_id, "image", 0, 1000, "name", "asc");
        foreach ($aAttachment["DS_IMAGE"] as $attach) {
            if ($attach["name"] != '') {
                $filename = "././resources/uploads/full/" . $attach["name"];
                if (file_exists($filename)) {
                    $pattern = '/' . $attach["name"] . '/';
                    preg_match_all($pattern, $body, $matches);

                    if (count($matches[0]) > 0) {
                        //scot calea relativa
                        $body = str_replace($path_full, "", $body);
                        //$sReplace="cid:".$attach["name"];
                        $aReplace = explode(".", $attach["name"]);
                        array_pop($aReplace);
                        $base = implode(".", $aReplace);
                        $sReplace2 = "cid:" . $base;

                        $body = str_replace($attach["name"], $sReplace2, $body);
                        $mail->AddEmbeddedImage($filename, $base, $attach["name"]);
                    }
                }
                else {

                    $aResponse = array("error" => true, "description" => "Un atasament nu exista", "error_no" => "2");
                }
            }
        }


        $mail->AddReplyTo($aTask->reply_email, $aTask->reply_name);
        $mail->SetFrom($aTask->from_email, $aTask->from_name);
		$sBodyStyle  = $aTask->body_style ; 
        $mail->Body = "<body {$sBodyStyle}>" . $body . "</body>";

	    if ($aResponse["error"] === TRUE) {
            echo json_encode($aResponse);
            return;
        }


        if (($aContact->email != "") && ($email == 1) ) { 
            try {

                $mail->AddAddress($aContact->email); //You can add more emails
                //$mail->AddAddress("daniel.darie@kimera.ro");

                if (!$mail->Send()) {
                    $aResponse =
                            array("error" => true, "description" => "Emailul NU a fost trimis: " . $mail->ErrorInfo);
                }
                else {
                    $aResponse = array("error" => false, "description" => "Emailul a fost trimis pe adresa de email 1");
                    $aTemp = array(
                        "client_persons_id" => $iContact,
                        "tl_operation_text" => "Trimitere email 1 " . $aContact->email, "tl_value" => $aContact->email,
                        "tl_operation" => "email", "user_id" => $this->aUser["user_id"]);
                    $this->db->insert("tele_log", $aTemp);
                }
            } catch (phpmailerException $e) {
                $aResponse = array("error" => true, "description" => "Emailul NU a fost trimis: " . $e->errorMessage());
            } catch (Exception $e) {
                $aResponse = array("error" => true, "description" => "Emailul NU a fost trimis: " . $e->getMessage());
            }
        }

        if (($aContact->email2 != "") && ($email == 2) ) {
            try {

                $mail->ClearAllRecipients();
                $mail->AddAddress($aContact->email2); //You can add more emails
                // $mail->AddAddress("daniel.darie@kimera.ro");

                if (!$mail->Send()) {
                    $aResponse =
                            array("error" => true, "description" => "Emailul NU a fost trimis: " . $mail->ErrorInfo);
                }
                else {
                    $aResponse = array("error" => false, "description" => "Emailul a fost trimis pe adresa email 2");
                    $aTemp = array(
                        "client_persons_id" => $iContact, "tl_operation" => "email",
                        "tl_operation_text" => "Trimitere email 2 " . $aContact->email2,
                        "tl_value" => $aContact->email2, "user_id" => $this->aUser["user_id"]);
                    $this->db->insert("tele_log", $aTemp);
                }
            } catch (phpmailerException $e) {
                $aResponse = array("error" => true, "description" => "Emailul NU a fost trimis: " . $e->errorMessage());
            } catch (Exception $e) {
                $aResponse = array("error" => true, "description" => "Emailul NU a fost trimis: " . $e->getMessage());
            }
        }
        echo json_encode($aResponse);
        return;
    }
}
